package dict

import (
	"abdis/interface/datastruct"
	"abdis/lib/wildcard"
)

type SimpleDict struct {
	m map[string]any
}

func MakeSimple() *SimpleDict {
	return &SimpleDict{
		m: make(map[string]any),
	}
}

func (d *SimpleDict) Get(key string) (any, bool) {
	val, ok := d.m[key]
	return val, ok
}

func (d *SimpleDict) Put(key string, val any) int {
	_, exists := d.m[key]
	d.m[key] = val
	if exists {
		return 0
	}
	return 1
}

func (d *SimpleDict) Len() int {
	return len(d.m)
}

func (d *SimpleDict) DictScan(cursor int, count int, pattern string) ([][]byte, int) {
	// TODO 实现不是很好
	ret := make([][]byte, 0)
	match, err := wildcard.CompilePattern(pattern)
	if err != nil {
		return ret, -1
	}
	for k, v := range d.m {
		if pattern == "*" || match.IsMatch(k) {
			//raw, exists := d.Get(k)
			//if !exists {
			//	continue
			//}
			ret = append(ret, []byte(k), v.([]byte))
		}
	}
	return ret, 0
}

func (d *SimpleDict) Remove(key string) (any, int) {
	val, exists := d.m[key]
	if !exists {
		return nil, 0
	}
	delete(d.m, key)
	return val, 1
}

func (d *SimpleDict) ForEach(consumer datastruct.Consumer) {
	for k, v := range d.m {
		if !consumer(k, v) {
			break
		}
	}
}
